import axios from 'axios';
import io from 'socket.io-client';
const socket = io('ws://localhost:9093');

//获取聊天列表
const MSG_LIST = 'MSG_LIST';
//读取信息
const MSG_RECV = 'MSG_RECV';
//标识已读
const MSG_READ = 'MSG_READ';

const initState = {
	chatmsg: [],
	unread: 0,
	users: {},
}

export function chat(state=initState, action) {
	switch(action.type) {
		case MSG_LIST:
			return {
				...state, 
				chatmsg: action.payload.msgs,
				users: action.payload.users, 
				// 过滤未读消息，只有是发给当前登录用户的，unread才加1
				unread: action.payload.msgs.filter(v => !v.read && v.to === action.payload.userid).length,
			}
		case MSG_RECV:
			// 过滤未读消息，只有是发给当前登录用户的，unread才加1
			const n = action.payload.userid === action.payload.msg.to ? 1 : 0;
			return {
				...state,
				chatmsg: [...state.chatmsg, action.payload.msg],
				unread: state.unread + n,
			}
		// case MSG_READ:
		default:
			return state
	}
}

function msgList(msgs, users, userid) {
	return {type: MSG_LIST, payload: {msgs, users, userid}}
}
function msgRecv(msg, userid) {
	return {type: MSG_RECV, payload: {msg, userid}}
}

export function recvMsg(data) {
	return (dispatch, getState) => {
		socket.on('recvMsg', function(data) {
			const userid = getState().user._id;
			dispatch(msgRecv(data, userid));
		})
	}
}
export function sendMsg({from, to, msg}) {
	return dispatch => {
		socket.emit('sendMsg', {from, to, msg});
	}
}
export function getMsgList() {
	return (dispatch, getState) => {
		axios.get('/user/getmsglist')
			.then(res => {
				if (res.status === 200 && res.data.code === 0) {
					const userid = getState().user._id;
					dispatch(msgList(res.data.msgs, res.data.users, userid));
				}
			})
	}
}